using WeatherApp.Services;
using WeatherApp.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 添加HTTP客户端
builder.Services.AddHttpClient();

// 添加内存缓存
builder.Services.AddMemoryCache();

// 添加Redis缓存（可选）
// builder.Services.AddStackExchangeRedisCache(options =>
// {
//     options.Configuration = builder.Configuration.GetConnectionString("Redis");
// });

// 配置数据库
builder.Services.AddDbContext<WeatherDbContext>(options =>
{
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
    if (string.IsNullOrEmpty(connectionString))
    {
        // 使用SQLite作为默认数据库
        connectionString = "Data Source=WeatherApp.db";
    }
    options.UseSqlite(connectionString);
});

// 注册服务
builder.Services.AddScoped<IWeatherService, WeatherService>();
builder.Services.AddScoped<IDataService, DataService>();

// 添加CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

var app = builder.Build();

// 确保数据库已创建
using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<WeatherDbContext>();
    context.Database.EnsureCreated();
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
else
{
    // 只在生产环境使用HTTPS重定向
    app.UseHttpsRedirection();
}

// 使用CORS
app.UseCors("AllowAll");

// 添加静态文件支持
app.UseStaticFiles();

app.UseAuthorization();

// 映射控制器
app.MapControllers();

// 添加健康检查端点
app.MapGet("/health", () => new { Status = "Healthy", Timestamp = DateTime.UtcNow });

// 添加API信息端点
app.MapGet("/api-info", () => new
{
    Name = "Weather API",
    Version = "1.0.0",
    Description = "天气查询服务API",
    Endpoints = new[]
    {
        "/api/weather/current/{city}",
        "/api/weather/forecast/{city}",
        "/api/weather/life-index/{city}",
        "/api/weather/search-cities?keyword={keyword}",
        "/api/weather/city-by-location?latitude={lat}&longitude={lon}",
        "/api/weather/complete/{city}",
        "/api/weather/history/{city}",
        "/api/weather/recent-records",
        "/api/usersettings/{userId}",
        "/api/usersettings/{userId}/favorites",
        "/api/usersettings/{userId}/history"
    }
});

app.Run();
